package com.ssm.controller;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.ssm.pojo.Email;
import com.ssm.pojo.User;
import com.ssm.service.UserService;
import com.ssm.util.R;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/user")
public class UserController {
	
	private static Logger logger = LoggerFactory.getLogger("logDailyFile"); 
	@Autowired
	private UserService userService;
	@Autowired
	private Producer producer;
	@Resource
	private Email mail;

	@RequestMapping("/page")
	public String toaddMainPage(){
		return "/user/main";
	}

	@RequestMapping("/showUserPage")
	public String toUserPage(){

		return "/user/user";
	}

	@RequestMapping("/showAddUser")
	public String toaddUserPage(){
		return "/user/addUser";
	}

	@RequestMapping("/showEditUser")
	public String toEditUserPage(String id,Model model)throws Exception{
		if (StringUtils.isEmpty(id)) {
			return "获取账户信息失败";

		}
		User user = new User();
		user.setId(id);
		List<User> rtUser = userService.get(user);
		model.addAttribute("user", rtUser.get(0));
		return "/user/editUser";
	}



	@RequestMapping("/sendMail")
	public void sendMails(){
		mail.sendMail("您好", "hello world", "790418787@qq.com");
	}
	
	@RequestMapping("/getCaptchaCode")
	public ModelAndView getCaptchaCode(HttpServletRequest request, HttpServletResponse response) throws IOException{
		HttpSession session = request.getSession();
		 response.setDateHeader("Expires", 0);  
		 response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");  
		 response.addHeader("Cache-Control", "post-check=0, pre-check=0");  
		 response.setHeader("Pragma", "no-cache");  
		 response.setContentType("image/jpeg"); 
		//生成验证码文本
		 String capText = producer.createText();  
		 session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
		 System.out.println("生成验证码文本===="+capText);
		 //利用生成的字符串构建图片
		 BufferedImage bi = producer.createImage(capText);
		// ServletOutputStream out = response.getOutputStream();
		 //ImageIO.write(bi, "jpg", out);在linux下不行

		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(response.getOutputStream());
		encoder.encode(bi);

//
//		 try {
//			  out.flush();
//			} finally {
//			 out.close();
//		 }
		return null;
	}
	 	@ResponseBody
	    @RequestMapping(value = "/submit")  
	    public R login(HttpServletRequest request, HttpServletResponse response,User user,@RequestParam("captchaCode") String captchaCode) throws Exception {  
	        System.out.println("name:" + user.getName() + "----" + "password:"  
	                + user.getPassword()+"页面输入验证码===="+captchaCode);  
	        
	        response.setCharacterEncoding("UTF-8");
	        response.setHeader("Pragma", "No-cache");
	        response.setHeader("Cache-Control", "no-cache");
	        response.setDateHeader("Expires", 0);
	        String generateCode =(String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
	        if(!generateCode.equals(captchaCode)){
	        	return R.error("验证码不正确");
	        }
	        Subject subject = SecurityUtils.getSubject();  
	        UsernamePasswordToken token = new UsernamePasswordToken(user.getName(),user.getPassword()); 
	        try {  
	            subject.login(token);
	        } catch (UnknownAccountException e) {
				return R.error(e.getMessage());
			}catch (IncorrectCredentialsException e) {
				return R.error(e.getMessage());
			}catch (LockedAccountException e) {
				return R.error(e.getMessage());
			}catch (AuthenticationException e) {
				return R.error("账户验证失败");
			}
	       // 登录成功  
	        request.getSession().setAttribute("info", user);
	        return R.ok();  
	    }
	 	/**
		 * 退出
		 */
		@RequestMapping(value = "logout", method = RequestMethod.GET)
		public String logout() {
			 SecurityUtils.getSubject().logout();
			return "login";
		}
	 
		@ResponseBody
		@RequestMapping(value = "/query", method = RequestMethod.GET)
		public PageInfo <User> findAllByPage(String pageNum,String pageSize) throws Exception{
			  PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
			  //设置排序
			  PageHelper.orderBy("createTime DESC");
			  
			  List<User> userList=userService.getAll();
				
			  PageInfo <User>  pager=new PageInfo <User>(userList);

			  return pager;
		}

		@ResponseBody
		@RequestMapping(value = "/showUserList")
		public R findAll(HttpServletRequest request,User user) throws Exception{

			String page = request.getParameter("page");
			String limit = request.getParameter("limit");
			PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(limit));
			//设置排序
			PageHelper.orderBy("createTime DESC");
			List<User> userList=userService.getAll();
			PageInfo <User>  pager=new PageInfo <User>(userList);

			Map<String, Object> map = new HashMap<>();

			map.put("data",pager.getList());
			map.put("count",pager.getTotal());
			map.put("code","0");
			map.put("msg","");

			return R.ok(map);
		}


	@ResponseBody
	@RequestMapping(value = "/getUser", method = RequestMethod.GET)
	public R get(HttpServletRequest request,User user) throws Exception {
		List<User> rtUser = userService.get(user);
		String page = request.getParameter("page");
		String limit = request.getParameter("limit");
		PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(limit));
		//设置排序
		PageHelper.orderBy("createTime DESC");
		PageInfo <User>  pager=new PageInfo <User>(rtUser);

		Map<String, Object> map = new HashMap<>();

		map.put("data",rtUser);
		map.put("count",rtUser.size());
		map.put("code","0");
		map.put("msg","");


		return R.ok(map);
	}
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> addUser(User user) {
		logger.info("用户注册成功");

		try{
			userService.addUser(user);
		}catch (Exception e){
			return R.error(0,e.getMessage());
		}
		return R.ok();

	}
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> deleteUser(User user) throws Exception {
		return userService.deleteUser(user);
	}
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> updateUser(User user) throws Exception {
		return userService.updateUser(user);
	}
	@RequestMapping(value = "/getQuery", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> getUser(User user) throws Exception {
		return userService.getUser(user);
	}

	
}
